package com.tally.framework.security.details;

import com.tally.common.constant.Constants;
import com.tally.framework.security.dto.LoginUser;
import com.tally.project.system.book.domain.Book;
import com.tally.project.system.book.service.IBookService;
import com.tally.project.system.user.domain.User;
import com.tally.project.system.user.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @Author soul
 * @Date 2023/5/14
 * @Description SpringSecurity登陆处理
 */
@Service
public class DetailsServiceImpl implements UserDetailsService {

	@Autowired
	private IUserService userService;

	@Autowired
	private IBookService bookService;


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 数据库验证账号
		User user = userService.loadUserByUsername(username);
		if (user == null) {
			throw new AuthenticationCredentialsNotFoundException("用户名不存在");
		} else if (user.getStatus() == Constants.LOCKED) {
			throw new LockedException("用户被锁定,请联系管理员");
		}

		// 获取账本
		List<Book> bookList = bookService.selectBookList(new Book(user.getUserId(),1));

		if (bookList.size() > 0){
			user.setBookId(bookList.get(0).getId());
		}

        return new LoginUser(username, user);
	}

	public static void main(String[] args) {
		// 创建密码加密的对象
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		// 密码加密
		String newPassword = passwordEncoder.encode("123456");
		System.out.println("加密后的密码为：" + newPassword);

	}

}
